package com.kk.service.impl;

import com.kk.constrants.RedisConstants;
import com.kk.pojo.dto.LoginUser;
import com.kk.pojo.entity.SysUser;
import com.kk.pojo.vo.UserPermissionVO;
import com.kk.service.SysRoleService;
import com.kk.service.SysUserService;
import com.kk.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RequiredArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService userService;
    private final SysRoleService roleService;
    private final RedisUtils redisUtils;  // ← 添加 RedisUtils

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户基本信息
        SysUser user = userService.getUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException(username);
        }

        // 2. 从 Redis 加载用户权限数据
        String redisKey = RedisConstants.USER_PREFIX + user.getId();
        UserPermissionVO permissionVO = redisUtils.get(redisKey);


        // 3. ✅ 构建自定义 LoginUser 对象
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());  // ← 设置 userId
        loginUser.setUsername(user.getUsername());
        loginUser.setPassword(user.getPassword());
        loginUser.setSysUser(user);

        if (permissionVO != null) {
            loginUser.setPermissions(permissionVO.getPermissions());
            loginUser.setRoles(permissionVO.getRoles());
        } else {
            loginUser.setPermissions(new HashSet<>());
            loginUser.setRoles(new HashSet<>());
        }

        return loginUser;  // ← 返回自定义对象
    }
}